package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import cn.com.elite.Util;
import java.net.URLEncoder;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

/**
 *
 * @Title: BP_CG_apiUnderdelivery
 * @Description:深圳宝安排水系统-数字化 工单数据下送接口--内部
 * @author: chieh* @date 2020-08-15 下午17:00:00
 *
 */

public class BP_CG_apiUnderdelivery implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(BP_CG_apiUnderdelivery.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = list.get(0).get("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {
			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());

			String sys_source = GetJV(inObject, "sys_source");
			String sys_flag = GetJV(inObject, "sys_flag");//1结案2回退  3申请时限  4申请延期
			String workorderid = GetJV(inObject, "workorderid");
			String time = GetJV(inObject, "time");
			log.debug("解析信息- sys_source：" + sys_source + 'sys_flag：' + sys_flag + 'workorderid：' + workorderid);

			def getSelectSQL = eliteBean.chaxun_sql("select o.curstep_id_map as curstep_id_map from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  where o.workorderid= '" + workorderid + "'", "dataSource");
			log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());
			String curstep_id_map = null;
			String dealMessage;
			if (getSelectSQL.size() > 0) {
				curstep_id_map = getSelectSQL.get(0).get("curstep_id_map");
				log.debug("工单步骤流程id：	" + curstep_id_map);
			} else {
				dealMessage = "当前处理的工单在CRM系统不存在！";
				return "{\"resultcode\":\"0\",\"resultmessage\":\"\",\"data\":\"" + dealMessage + "\"}";
			}

			//结案1
			if (sys_source == 'CG' && sys_flag == '1') {  // && curstep_id_map == 'KNGZL4'
				outData = CGCaseClosed(sys_source, workorderid, eliteBean);
				//回退2
			} else if (sys_source == 'CG' && sys_flag == '2' && curstep_id_map == 'O70W2B') {
				outData = CGCaseBack(sys_source, workorderid, eliteBean);
				//申请时限3
			} else if (sys_source == 'CG' && sys_flag == '3' && curstep_id_map == 'O70W2B') {
				outData = CGEvtTimeChgReq(sys_source, workorderid, eliteBean);
				//申请延时4
			} else if (sys_source == 'CG' && sys_flag == '4' && curstep_id_map == 'O70W2B') {
				outData = CGEvtTimeChgReqSave(sys_source, workorderid, time, eliteBean);
			} else {
				dealMessage = "当前处理的工单在CRM系统工单步骤不在话务员处理:" + curstep_id_map + "节点！";
				return "{\"resultcode\":\"0\",\"resultmessage\":\"\",\"data\":\"" + dealMessage + "\"}";
			}

	    } catch (Exception e) {// 失败返回
		    log.error("接口处理异常" + e.getMessage());
	        outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):2\",\"data\":[]}";

	    }
		log.debug("完成返回结果:" + outData);

		return outData;
	}

	//调用数字化结案接口
	public static String CGCaseClosed(String sys_source, String workorderid, EliteBean eliteBean) {
		long startTime = System.currentTimeMillis();
		def szhtok;
		def szhtokresult = eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'SZHTOK' and MODIFIEDDATE>GETDATE()", "dataSource");
		if (szhtokresult.size() > 0) {
			szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
			log.debug("szhtok:	" + szhtok);
		}
		if (szhtok == null) {
			szhtok = getCaseTasks(eliteBean);
		}
		log.debug("szhtok1:	" + szhtok);

		def getSelectSQL = eliteBean.chaxun_sql("select t.evtID as evtID,t.actInstID as actInstID,o.comments as comments,o.objective_guid as objective_guid from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  LEFT JOIN SZWG_DE_Case_Tasks sct on sct.actID=t.evtID  where o.workorderid= '" + workorderid + "'", "dataSource");
		String evtID = getSelectSQL.get(0).get("evtID");
		String actInstID = getSelectSQL.get(0).get("actInstID");
		String comments = getSelectSQL.get(0).get("comments");
		String objective_guid = getSelectSQL.get(0).get("objective_guid");
		String TPNWURL = getProperty.get("CRM.TPNWURL");
		def getSelectUploadSQL = eliteBean.chaxun_sql("select case type when	3  then '"+TPNWURL+"'+path  else Replace(path,'https://yg.szbaps.com:8080','http://10.44.85.12:8080') end as path,name,OPERATIONTIME,filedesc from rm_uploadrecord where  type  in ('3','4') and objectiveid='" + objective_guid + "'", "dataSource");
		Map<String, Object> map = new HashMap<String, Object>();
		JSONArray json1 = new JSONArray();
		for (int i = 0; i < getSelectUploadSQL.size(); i++) {
			JSONObject jo = new JSONObject();
			jo.put("imgHref", getSelectUploadSQL.get(i).get("path"));
			jo.put("mediaId", getSelectUploadSQL.get(i).get("mediaId"));
			jo.put("mediaType", "0");
			json1.put(jo);
		}
		String js1 = json1.toString();
		String js2 = js1.replaceAll("\"imgHref\"", "imgHref").replaceAll("\"mediaId\"", "mediaId").replaceAll("\"mediaType\"", "mediaType").replaceAll("\"0\"", "0");
		log.debug("getSelectUploadSQLjs1:" + js2);
		log.debug("getSelectUploadSQL:" + getSelectUploadSQL);
		log.debug("json1" + json1);
		String json = "{id:" + evtID + ",actInstID:" + actInstID + ",content:\"" + comments + "\",img:"+js2+"}";

		String reJson = null;
		try {
			String URL = getProperty.get("SZCG.URL") + "/swEvent/EvtProcess?access_token=" + szhtok;

			// 设置头文件
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			log.debug("调用地址URL：" + URL);
			log.debug("调用发送报文信息：" + json);
			String injson = Util.doHttpPostUseHead(URL, json, "UTF-8", 100000, 0, headMap);

			log.debug("调用返回信息：" + injson.toString());
			JSONObject inObject = new JSONObject(injson);
			String statusCode = KHUtil.GetJV(inObject, "statusCode");
			String errorMsg = string2Json(KHUtil.GetJV(inObject, "errorMsg"));

			long endTime = System.currentTimeMillis();
			if (statusCode.equals("0")) {
				reJson = "{\"resultcode\":\"" + 1 + "\",\"resultmessage\":\"BP智慧化数字化结案接口处理成功,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":\"" + errorMsg + "\"}";
			} else {
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化数字化结案接口处理失败(" + errorMsg + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
			}
	    } catch (JSONException e) {
		    long endTime = System.currentTimeMillis();
		    reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化数字化结案接口处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
		}
		return reJson;
	}

	//调用数字化回退接口
	public static String CGCaseBack(String sys_source, String workorderid, EliteBean eliteBean) {
		long startTime = System.currentTimeMillis();
		def szhtok;
		def szhtokresult = eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'SZHTOK' and MODIFIEDDATE>GETDATE()", "dataSource");
		if (szhtokresult.size() > 0) {
			szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
			log.debug("szhtok:	" + szhtok);
		}
		if (szhtok == null) {
			szhtok = getCaseTasks(eliteBean);
		}
		log.debug("szhtok1:	" + szhtok);

		def getSelectSQL = eliteBean.chaxun_sql("select o.objective_guid as objective_guid,t.evtID as evtID,t.actInstID as actInstID,o.comments as comments from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  LEFT JOIN SZWG_DE_Case_Tasks sct on sct.actID=t.evtID  where o.workorderid= '" + workorderid + "'", "dataSource");
		String objective_guid = getSelectSQL.get(0).get("objective_guid");
		String evtID = getSelectSQL.get(0).get("evtID");
		String actInstID = getSelectSQL.get(0).get("actInstID");
		String comments = getSelectSQL.get(0).get("comments");
		String TPNWURL = getProperty.get("CRM.TPNWURL");
		
		def getSelectUploadSQL = eliteBean.chaxun_sql("select case type when	3  then '"+TPNWURL+"'+path  else Replace(path,'https://yg.szbaps.com:8080','http://10.44.85.12:8080') end as path,name,OPERATIONTIME,filedesc from rm_uploadrecord where type  in ('3','4')  and objectiveid='" + objective_guid + "'", "dataSource");
		Map<String, Object> map = new HashMap<String, Object>();
		JSONArray json1 = new JSONArray();
		for (int i = 0; i < getSelectUploadSQL.size(); i++) {
			JSONObject jo = new JSONObject();
			jo.put("imgHref", getSelectUploadSQL.get(i).get("path"));
			jo.put("mediaId", getSelectUploadSQL.get(i).get("mediaId"));
			jo.put("mediaType", "0");
			json1.put(jo);
		}
		String js1 = json1.toString();
		String js2 = js1.replaceAll("\"imgHref\"", "imgHref").replaceAll("\"mediaId\"", "mediaId").replaceAll("\"mediaType\"", "mediaType").replaceAll("\"0\"", "0");
//		js1.replaceAll("\"name\"","name");
//		js1.replaceAll("\"OPERATIONTIME\"","OPERATIONTIME");
		log.debug("getSelectUploadSQLjs1:" + js2);
		log.debug("getSelectUploadSQL:" + getSelectUploadSQL);
		log.debug("json1" + json1);
		String json = "{id:" + evtID + ",actInstID:" + actInstID + ",content:\"" + comments + "\",img:"+js2+"}";
		log.debug("json:"+json)
		String reJson = null;
		try {
			String URL = getProperty.get("SZCG.URL") + "/swEvent/ReturnBack?access_token=" + szhtok;

			// 设置头文件
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			log.debug("调用地址URL：" + URL);
			log.debug("调用发送报文信息：" + json);
			String injson = Util.doHttpPostUseHead(URL, json, "UTF-8", 100000, 0, headMap);

			log.debug("调用返回信息：" + injson.toString());
			JSONObject inObject = new JSONObject(injson);
			String statusCode = KHUtil.GetJV(inObject, "statusCode");
			String errorMsg = string2Json(KHUtil.GetJV(inObject, "errorMsg"));

			long endTime = System.currentTimeMillis();
			if (statusCode.equals("0")) {
				reJson = "{\"resultcode\":\"" + 1 + "\",\"resultmessage\":\"BP智慧化数字化回退接口处理成功,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":\"" + errorMsg + "\"}";
			} else {
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化数字化回退接口处理失败(" + errorMsg + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
			}
		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化数字化回退接口处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
		}
		return reJson;
	}

	//调用数字化申请时限接口
	public static String CGEvtTimeChgReq(String sys_source, String workorderid, EliteBean eliteBean) {
		long startTime = System.currentTimeMillis();
		def szhtok;
		def szhtokresult = eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'SZHTOK' and MODIFIEDDATE>GETDATE()", "dataSource");
		if (szhtokresult.size() > 0) {
			szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
			log.debug("szhtok:	" + szhtok);
		}
		if (szhtok == null) {
			szhtok = getCaseTasks(eliteBean);
		}
		log.debug("szhtok1:	" + szhtok);

		def getSelectSQL = eliteBean.chaxun_sql("select t.evtID as evtID,t.actInstID as actInstID ,o.customer_guid as  customer_guid from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  LEFT JOIN SZWG_DE_Case_Tasks sct on sct.actID=t.evtID  where o.workorderid= '" + workorderid + "'", "dataSource");
		String evtID = getSelectSQL.get(0).get("evtID");
		String actInstID = getSelectSQL.get(0).get("actInstID");
		String customer_guid = getSelectSQL.get(0).get("customer_guid");
		log.debug("customer_guid"+customer_guid);
		if(!customer_guid.equals("2                                   ")){
			long endTime = System.currentTimeMillis();
		String	reJson = "{\"resultcode\":\"" + 0 + "\",\"resultmessage\":\"当前工单非数字化城管工单，延期失败；调用问题处理时长(毫秒)" + (endTime - startTime) + "\",\"data\":{}}";
			return reJson;
		}

		String json = "{id:" + evtID + ",actInstID:" + actInstID + "}";
		String reJson = null;
		try {
			String URL = getProperty.get("SZCG.URL") + "/swEvent/EvtTimeChgReq?access_token=" + szhtok;

			// 设置头文件
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			log.debug("调用地址URL：" + URL);
			log.debug("调用发送报文信息：" + json);
			String injson = Util.doHttpPostUseHead(URL, json, "UTF-8", 100000, 0, headMap);

			log.debug("调用返回信息：" + injson.toString());
			JSONObject inObject = new JSONObject(injson);
			String statusCode = KHUtil.GetJV(inObject, "statusCode");
			String errorMsg = string2Json(KHUtil.GetJV(inObject, "errorMsg"));
			String result = KHUtil.GetJV(inObject, "result");

			long endTime = System.currentTimeMillis();
			if (statusCode.equals("0")) {
				reJson = "{\"resultcode\":\"" + 1 + "\",\"resultmessage\":\"BP智慧化数字化申请时限接口处理成功,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + result + "}";
			} else {
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化数字化申请时限接口处理失败(" + errorMsg + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
			}
		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化数字化申请时限接口处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
		}
		return reJson;
	}

	//调用数字化申请延时接口
	public static String CGEvtTimeChgReqSave(String sys_source, String workorderid, String time, EliteBean eliteBean) {
		long startTime = System.currentTimeMillis();
		def szhtok;
		def szhtokresult = eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'SZHTOK' and MODIFIEDDATE>GETDATE()", "dataSource");
		if (szhtokresult.size() > 0) {
			szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
			log.debug("szhtok:	" + szhtok);
		}
		if (szhtok == null) {
			szhtok = getCaseTasks(eliteBean);
		}
		log.debug("szhtok1:	" + szhtok);

		def getSelectSQL = eliteBean.chaxun_sql("select t.evtID as evtID,t.actInstID as actInstID,o.comments as comments,o.customer_guid from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  LEFT JOIN SZWG_DE_Case_Tasks sct on sct.actID=t.evtID  where o.workorderid= '" + workorderid + "'", "dataSource");
		String evtID = getSelectSQL.get(0).get("evtID");
		String actInstID = getSelectSQL.get(0).get("actInstID");
		String comments = getSelectSQL.get(0).get("comments");
		String customer_guid = getSelectSQL.get(0).get("customer_guid");
		log.debug("customer_guid===="+customer_guid);
		if(!customer_guid.equals("2                                   ")){
			long endTime = System.currentTimeMillis();
			String	reJson = "{\"resultcode\":\"" + 0 + "\",\"resultmessage\":\"当前工单非数字化城管工单，延期失败；调用问题处理时长(毫秒)" + (endTime - startTime) + "\",\"data\":{}}";
			return reJson;
		}

		String json = "{id:" + evtID + ",actInstID:" + actInstID + ",time:\"" + time + "\",content:\"" + comments + "\"}";
		String reJson = null;
		try {
			String URL = getProperty.get("SZCG.URL") + "/swEvent/EvtTimeChgReqSave?access_token=" + szhtok;

			// 设置头文件
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			log.debug("调用地址URL：" + URL);
			log.debug("调用发送报文信息：" + json);
			String injson = Util.doHttpPostUseHead(URL, json, "UTF-8", 100000, 0, headMap);

			log.debug("调用返回信息：" + injson.toString());
			JSONObject inObject = new JSONObject(injson);
			String statusCode = KHUtil.GetJV(inObject, "statusCode");
			String errorMsg = string2Json(KHUtil.GetJV(inObject, "errorMsg"));

			long endTime = System.currentTimeMillis();
			if (statusCode.equals("0")) {
				reJson = "{\"resultcode\":\"" + 1 + "\",\"resultmessage\":\"BP智慧化数字化申请延时接口调度成功,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":\"" + errorMsg + "\"}";
			} else {
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化数字化申请延时接口处理失败(" + errorMsg + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
			}
		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化数字化申请延时接口处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
		}
		return reJson;
	}

	// 获取token
	public static String getCaseTasks(EliteBean eliteBean) {
		log.debug("-------------------------start Bp_Get_CGToKen 开始-----------------");
		def sysurl = "http://127.0.0.1:8080/EliteGeneralHttpTask/GeneralService/Bp_Get_CGToKen";
		String reJson = Util.doHttpGet(sysurl, "UTF-8", 10000, 0);
		JSONObject inObject = new JSONObject(reJson);
		log.debug("ToKen报文：" + reJson);

		String resultcode = KHUtil.GetJV(inObject, "resultcode");
		String data = KHUtil.GetJV(inObject, "data");
		log.debug("resultcode	" + resultcode);
		log.debug("data	" + data);

		return data;
	}

	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
	
	public static String string2Json(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i=0; i<s.length(); i++) {
			char c = s.charAt(i);
			 switch (c){
			 case '\"':
				 sb.append("\\\"");
				 break;
			 case '\\':
				 sb.append("\\\\");
				 break;
			 case '/':
				 sb.append("\\/");
				 break;
			 case '\b':
				 sb.append("\\b");
				 break;
			 case '\f':
				 sb.append("\\f");
				 break;
			 case '\n':
				 sb.append("\\n");
				 break;
			 case '\r':
				 sb.append("\\r");
				 break;
			 case '\t':
				 sb.append("\\t");
				 break;
			 default:
				 sb.append(c);
			 }
		 }
		return sb.toString();
	}

}
